package com.ishitong.platform.utils.hibernate;

import org.hibernate.usertype.UserType;
import org.hibernate.HibernateException;
import org.hibernate.util.EqualsHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Types;
import java.io.Serializable;
import java.util.Date;

/**
 * 为了解决Hibernate保存Date型字段时丢失毫秒数的情况，自定义了UserType来保存Date型字段，将Date型转换为long型保存到数据库中。
 * 
 * @author MarkDong
 * @since 2.0
 */
public class DateType implements UserType {

	public int[] sqlTypes() {
		return new int[] { Types.BIGINT };
	}

	public Class returnedClass() {
		return Date.class;
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		return EqualsHelper.equals(x, y);
	}

	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
		Long millions = rs.getLong(names[0]);
		return new Date(millions);
	}

	public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
		if (value == null) {
			st.setNull(index, Types.BIGINT);
		} else {
			Long millions = ((Date) value).getTime();
			st.setLong(index, millions);
		}
	}

	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	public boolean isMutable() {
		return false;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}
}
